package org.dromara.system.controller.xcx;

import cn.dev33.satoken.annotation.SaCheckPermission;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.system.domain.bo.*;
import org.dromara.system.domain.dto.WbCandidateListDTO;
import org.dromara.system.domain.vo.*;
import org.dromara.system.service.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 小程序-用户
 *
 * @author Lion Li
 * @date 2024-05-08
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xcx/user")
public class UserController extends BaseController {

    private final IXcxFollowService xcxFollowService;

    private final IXcxFootprintService xcxFootprintService;

    private final ISysUserService sysUserService;

    private final IWbCompanyInfoService wbCompanyInfoService;

    private final IWbItemInfoService wbItemInfoService;

    private final IWbCandidateListService wbCandidateListService;

    private final ISysNoticeService noticeService;

    private final IZtUserVipService ztUserVipService;

    private final IXcxSubscribeKeywordService xcxSubscribeKeywordService;
    private final IXcxSubscribeProjectUnitService xcxSubscribeProjectUnitService;
    private final IWbGoodsListInfoService wbGoodsListInfoService;
    private final IGzhUserService gzhUserService;
    /**
     * 判断用户是否关注公众号
     */
    @GetMapping("/gzhUser")
    public R<GzhUserVo> gzhUserList() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        Long userId = loginUser.getUserId();
        GzhUserVo gzhUserVo = gzhUserService.queryGzhById(userId);
        if (gzhUserVo != null){
            return R.ok(gzhUserVo);
        }
        return R.fail("您还没关注公众哟！");
    }
    /**
     * 查询物资清单
     */
    @GetMapping("/wbGoodsListInfo/list")
    public TableDataInfo<WbGoodsListInfoVo> wbGoodsListInfo(WbGoodsListInfoBo bo, PageQuery pageQuery) {
        return wbGoodsListInfoService.queryPageGoodsList(bo, pageQuery);
    }
    /**
     * 查询订阅关键字列表
     */
    @GetMapping("/subscribeKeyword/list")
    public TableDataInfo<XcxSubscribeKeywordVo> list(XcxSubscribeKeywordBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        bo.setUserId(userId);
        return xcxSubscribeKeywordService.queryPageList(bo, pageQuery);
    }
    /**
     * 获取订阅关键字详细信息
     *
     * @param id 主键
     */
    @GetMapping("/subscribeKeyword/{id}")
    public R<XcxSubscribeKeywordVo> getSubscribeKeywordInfo(@NotNull(message = "主键不能为空")
                                            @PathVariable Long id) {
        return R.ok(xcxSubscribeKeywordService.queryById(id));
    }
    /**
     * 新增订阅关键字
     */
    @PostMapping("/subscribeKeyword")
    public R<Void> add(@Validated(AddGroup.class) @RequestBody XcxSubscribeKeywordBo bo) {
        Long userId = LoginHelper.getUserId();
        XcxSubscribeKeywordBo bo1 = new XcxSubscribeKeywordBo();
        bo1.setUserId(userId);
        bo.setUserId(userId);
        // 判断用户是否为vip用户或者以是否添加三个
        if(ztUserVipService.queryVipUser(userId) != null || xcxSubscribeKeywordService.queryList(bo1).size() <= 2) {
            return toAjax(xcxSubscribeKeywordService.insertByBo(bo));
        }else {
            return R.fail("添加失败，非会员用户最多只能添加三个关键字。");
        }
    }
    /**
     * 删除订阅关键字
     *
     * @param ids 主键串
     */
    @DeleteMapping("/subscribeKeyword/{ids}")
    public R<Void> subscribeKeywordRemove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(xcxSubscribeKeywordService.deleteWithValidByIds(List.of(ids), true));
    }
    /**
     * 查询订阅项目单位列表
     */
    @GetMapping("/subscribeProjectUnit/list")
    public TableDataInfo<XcxSubscribeProjectUnitVo> list(XcxSubscribeProjectUnitBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        bo.setUserId(userId);
        return xcxSubscribeProjectUnitService.queryPageList(bo, pageQuery);
    }



    /**
     * 获取订阅项目单位详细信息
     *
     * @param id 主键
     */
    @GetMapping("/subscribeProjectUnit/{id}")
    public R<XcxSubscribeProjectUnitVo> subscribeProjectUnitGetInfo(@NotNull(message = "主键不能为空")
                                                @PathVariable Long id) {
        return R.ok(xcxSubscribeProjectUnitService.queryById(id));
    }

    /**
     * 新增订阅项目单位
     */
    @PostMapping("/subscribeProjectUnit")
    public R<Void> add(@Validated(AddGroup.class) @RequestBody XcxSubscribeProjectUnitBo bo) {
        Long userId = LoginHelper.getUserId();
        bo.setUserId(userId);
        return toAjax(xcxSubscribeProjectUnitService.insertByBo(bo));
    }


    /**
     * 删除订阅项目单位
     *
     * @param ids 主键串
     */
    @DeleteMapping("/subscribeProjectUnit/{ids}")
    public R<Void> subscribeProjectUnitRemove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(xcxSubscribeProjectUnitService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 获取通知公告列表
     */
    @GetMapping("/notice/list")
    public TableDataInfo<SysNoticeVo> list(SysNoticeBo notice, PageQuery pageQuery) {
        return noticeService.selectPageNoticeList(notice, pageQuery);
    }

    /**
     * 根据通知公告编号获取详细信息
     *
     * @param noticeId 公告ID
     */
    @GetMapping(value = "/notice/{noticeId}")
    public R<SysNoticeVo> getInfo(@PathVariable Long noticeId) {
        return R.ok(noticeService.selectNoticeById(noticeId));
    }



    /**
     * 查询我的关注列表
     */
    @GetMapping("/follow/list")
    public TableDataInfo<XcxFollowVo> list(XcxFollowBo bo, PageQuery pageQuery) {
        bo.setCreateBy(LoginHelper.getUserId());
        return xcxFollowService.queryPageListXcx(bo, pageQuery);
    }

    /**
     * 新增我的关注
     */
    @PostMapping("/follow/add")
    public R<Void> add(@RequestBody XcxFollowBo bo) {
        bo.setCreateBy(LoginHelper.getUserId());
        return toAjax(xcxFollowService.insertByBo(bo));
    }

    /**
     * 查询我的足迹列表
     */
    @GetMapping("/footprint/list")
    public TableDataInfo<XcxFootprintVo> list(XcxFootprintBo bo, PageQuery pageQuery) {
        bo.setCreateBy(LoginHelper.getUserId());
        return xcxFootprintService.queryPageListXcx(bo, pageQuery);
    }

    /**
     * 删除我的足迹
     *
     * @param ids 主键串
     */
    @Log(title = "我的足迹", businessType = BusinessType.DELETE)
    @DeleteMapping("/footprint/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(xcxFootprintService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 查询用户基础信息（基础信息、关注数量、足迹数量）
     */
    @GetMapping("/getInfo")
    public R<SysUserVo> getInfo() {
        return R.ok(sysUserService.getInfo());
    }

    /**
     * 设置用户关联的企业
     * @param id 企业ID
     * @return
     */
    @GetMapping("/setEnterprise/{id}")
    public R<Void> setEnterprise(@NotNull(message = "企业ID不能为空") @PathVariable("id") Long id) {
        WbCompanyInfoVo wbCompanyInfoVo = wbCompanyInfoService.queryById(id);
        if(wbCompanyInfoVo != null){
            return toAjax(sysUserService.updateUserEnterprise(LoginHelper.getUserId(),wbCompanyInfoVo.getId()));
        }
        return R.fail("关联企业无效");
    }

    /**
     * 查询我的资质
     */
    @GetMapping("/getCompanyInfo")
    public R<WbCompanyInfoVo> getCompanyInfo() {
        SysUserVo sysUserVo = sysUserService.selectUserById(LoginHelper.getUserId());
        if(sysUserVo.getEnterpriseId() != null){
            WbCompanyInfoVo wbCompanyInfoVo = wbCompanyInfoService.queryByIdZdy(sysUserVo.getEnterpriseId());
            return R.ok(wbCompanyInfoVo);
        }
        return R.ok();
    }


    @GetMapping ("/itemInfo/winningTheBid")
    public R<WbCompanyInfoVo> winningTheBid() {
        SysUserVo sysUserVo = sysUserService.selectUserById( LoginHelper.getUserId());
        if(sysUserVo.getEnterpriseId() != null){
            WbCompanyInfoVo wbCompanyInfoVo = wbCompanyInfoService.queryByIdZdy(sysUserVo.getEnterpriseId());
            return R.ok(wbCompanyInfoVo);
        }
        return R.fail("请先绑定企业");
    }
    @GetMapping ("/itemInfo/winningTheBidZYT")
    public TableDataInfo<WbCandidateListVo> winningTheBidZYT(String year,String provinceId,PageQuery pageQuery) {
        SysUserVo sysUserVo = sysUserService.selectUserById( LoginHelper.getUserId());
        if(sysUserVo.getEnterpriseId() != null) {
            TableDataInfo<WbCandidateListVo> wbCandidateListVoTableDataInfo = wbCandidateListService.queryByList(year,provinceId,sysUserVo.getEnterpriseId(), pageQuery);
            return wbCandidateListVoTableDataInfo;
        }
        return TableDataInfo.build();
    }
    /**
     * 查询我的捷报
     * @param
     * @return
     */
    @PostMapping ("/itemInfo/goodNews")
    public TableDataInfo<WbCandidateListDTO> goodNews(@RequestBody PageQuery pageQuery) {
        SysUserVo sysUserVo = sysUserService.selectUserById(LoginHelper.getUserId());
        if(sysUserVo.getEnterpriseId() != null){
            SysUserBo sysUserBo = new SysUserBo();
            sysUserBo.setUserId(sysUserVo.getUserId());
            // 获取当前时间
            Date date = new Date(System.currentTimeMillis());
            // 定义日期时间格式
            SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 格式化当前时间为字符串
            String format = formatter.format(date);
            try {
                sysUserBo.setLastLoginTime(formatter.parse(format));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            /**
             * 修改用户最后一次查看捷报时间
             */
            sysUserService.updateUser(sysUserBo);
            return wbItemInfoService.queryListZdy(sysUserVo.getEnterpriseId(), pageQuery);
        }
        return TableDataInfo.build();
    }

    /**
     * 首页
     * 查询我的捷报
     * @returnZYP
     */
    @PostMapping ("/itemInfo/goodNewsZ")
    public TableDataInfo<WbCandidateListDTO> goodNewsZ() {
        SysUserVo sysUserVo = sysUserService.selectUserById(LoginHelper.getUserId());
        if(sysUserVo.getEnterpriseId() != null){
            SysUserBo sysUserBo = new SysUserBo();
            sysUserBo.setUserId(sysUserVo.getUserId());
            // 获取当前时间
            Date date = new Date(System.currentTimeMillis());
            // 定义日期时间格式
            SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 格式化当前时间为字符串
            String format = formatter.format(date);
            try {
                sysUserBo.setLastLoginTime(formatter.parse(format));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            /**
             * 修改用户最后一次查看捷报时间
             */
            sysUserService.updateUser(sysUserBo);
            return wbItemInfoService.queryListZ(sysUserVo.getEnterpriseId(),sysUserVo.getUserId());
        }
        return TableDataInfo.build();
    }

}
